// pages/write-off/order-ok.js
const numeral = require("../../vendor/numeral/numeral.min")
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        num: 1,
        travelerList: [],
        complete: true,
        chooseTraveler: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setData(options)
        this.loadData()
    },
    onShow() {
        app.http.get('hx-goods/member-object-list').then(res => {
            this.setData({
                travelerList: res.data.list
            })
            if (app.travelerList) {
                var chooseTraveler = []
                app.travelerList.forEach((o) => {
                    this.data.travelerList.forEach((a) => {
                        if (o == a.object_id) {
                            chooseTraveler.push({
                                object_id: a.object_id,
                                consignee: a.real_name,
                                tel: a.tel,
                                id_card: a.card_value
                            })
                        }
                    })
                })
                this.setData({
                    chooseTraveler
                })
            }
        })

    },
    loadData() {
        if (!this.data.id) {
            return
        }
        wx.showLoading({
            title: '加载中...',
        })
        Promise.all([
            app.http.get('hx-goods/base-info', {
                data: {
                    id: this.data.id,
                    sku_id: this.data.sku_id ? this.data.sku_id : ''
                }
            }),
            app.http.get('user/get-message'),
            app.http.get('hx-goods/order-object-config?goods_id=' + this.data.id),

        ]).then(res => {
            this.setData({
                goods_info: res[0].data,
                [`traveler.tel`]: res[1].data.mobile,
                is_open: res[2].data.is_open, //0否 1是
            })
            app.orderConfig = res[2].data.config
            wx.hideLoading()
            this.totalPrice()
        })
    },
    //出行人
    addTraveler() {
        wx.navigateTo({
            url: '/pages/write-off/traveler-input',
        })
    },
    deleteTraveler(evt) {
        let index = evt.currentTarget.dataset.index
        let chooseTraveler = this.data.chooseTraveler
        chooseTraveler.splice(index, 1)
        this.setData({
            chooseTraveler
        })
        app.travelerList.splice(index, 1)
    },
    update(evt) {
        let index = evt.currentTarget.dataset.index
        let params = this.data.chooseTraveler[index]
        console.log(params, 'params')
        let paramsArr = []
        Object.keys(params).forEach(k => {
            paramsArr.push(k + "=" + params[k])
        })
        wx.navigateTo({
            url: '/pages/write-off/update-traveler' + '?' + paramsArr.join('&'),
        })
    },
    bindinput(evt) {
        let key = evt.currentTarget.dataset.key
        let value = evt.detail.value
        this.setData({
            [`${key}`]: value ? value : '',
        })
    },
    /**
     * 修改数量
     */
    numClick(evt) {
        let dset = evt.currentTarget.dataset;
        let {
            index,
            step
        } = dset
        let {
            sku_info = {}, stock = 0, max_buy_num = 0
        } = this.data.goods_info
        let num = parseInt(this.data.num) + parseInt(step)
        stock = sku_info.stock ? sku_info.stock : stock
        if (num < 1) {
            wx.showToast({
                icon: 'none',
                title: '宝贝不能再减少啦~',
            })
            return
        }
        if (num > stock) {
            wx.showToast({
                icon: 'none',
                title: '库存不足啦~',
            })
            return
        }
        if (num > max_buy_num && max_buy_num != 0) {
            wx.showToast({
                icon: 'none',
                title: '宝贝已到达最大购买数~',
            })
            return
        }
        this.setData({
            num,
        })
        this.totalPrice()
    },
    totalPrice() {
        let goods = this.data.goods_info
        let price = goods.sku_info ? goods.sku_info.mall_price : goods.mall_price
        let total = parseFloat(price) * this.data.num
        this.setData({
            totalPrice: numeral(total).format("0,0.00")
        })
    },

    submit() {
        let {
            chooseTraveler = [], paying = false, num = 1, remark = '', traveler = {}
        } = this.data
        if (this.data.is_open == 0) { //订单信息
            if (!traveler.consignee) {
                wx.showToast({
                    icon: 'none',
                    title: '请输入姓名',
                })
                return
            }
            let reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
            if (!reg.test(traveler.tel)) {
                wx.showToast({
                    icon: 'none',
                    title: '手机号不正确',
                })
                return
            }
            chooseTraveler = []
            chooseTraveler.push(traveler)
        }
        if (chooseTraveler.length == 0) {
            wx.showToast({
                icon: 'none',
                title: '请选择出行人',
            })
            return
        }
        if (paying) return
        this.setData({
            paying: true
        })
        wx.showLoading({
            title: '请稍等',
        })
        let data = {
            quantity: num,
            goods_id: this.data.id,
            remark: remark,
            objects: chooseTraveler,
            sku_id: this.data.sku_id ? this.data.sku_id : ''
        }
        app.http.post('hx-order/create', {
            data
        }).then(res => {
            wx.hideLoading()
            let jsPay = res.data.js
            let order_id = res.data.order_id
            this.setData({
                paying: false
            })
            if (res.data.pay_type == 2) {
                wx.showToast({
                    icon: 'none',
                    title: '支付成功',
                })
                wx.redirectTo({
                    url: '/pages/write-off/order-detail?order_id=' + order_id,
                })
                return
            }
            if (jsPay) {
                const obj = Object.assign(jsPay, {
                    success: res => {
                        wx.showToast({
                            icon: 'none',
                            title: '支付成功',
                        })
                        wx.redirectTo({
                            url: '/pages/write-off/order-detail?order_id=' + order_id,
                        })
                    },
                    fail: err => {
                        wx.showToast({
                            icon: 'none',
                            title: '支付取消',
                        })
                        wx.redirectTo({
                            url: '/pages/write-off/order-detail?order_id=' + order_id,
                        })
                    }
                });
                wx.requestPayment(obj)
            }
        }).catch(err => {
            console.log(err.message)
            app.wxToast.error(err.message)
            this.setData({
                paying: false
            })
        })
    }
})